#!/bin/python

import configparser
import json
import os

class ConfigModule():
    @classmethod
    def load(cls, path):
        _ext = os.path.splitext(path)[1]
        if '.json' == _ext:
            return cls.load_from_json(path)
        return cls.load_from_ini(path)

    @classmethod
    def load_from_json(cls, path):
        with open(path, 'r') as f:
            return cls(json.load(f))
    @classmethod
    def load_from_ini(cls, path):
        _dict = {}
        _parser = configparser.ConfigParser(inline_comment_prefixes=())
        with open(path, "r") as f_conf:
            _parser.read_file(f_conf)
        for s in _parser.sections():
            _dict[s] = {}
            for n, v in _parser.items(s):
                _dict[s][n] = v
        return cls(_dict)

    def __init__(self, _dict):
        self.config_dict = _dict

    #def get_value(self, section, field, default):
    def get_value(self, *argv):
        if len(argv) < 2:
            return None
        section = argv[0]
        default = argv[-1]
        if section not in self.config_dict:
            return default
        if len(argv) > 2:
            field = argv[1]
            if field not in self.config_dict[section]:
                return default
            _value = self.config_dict[section][field]
        else:
            _value = self.config_dict[section]
        if isinstance(default, float):
            return float(_value)
        return _value

    def get_string(self, section, field, default):
        return self.get_value(section, field, default)

if __name__ == '__main__':
    myconfig = ConfigModule({
        'my': {
            'love': -32
        }
    })
    print(myconfig.get_value("my", "love", -32))
    print(myconfig.get_value("unknown", "love2", 32323232233))
    print(myconfig.get_value("my", "love3", 3232.4343))
    print(myconfig.get_value("my", {}))
    print(myconfig.get_string("my", "love1", "jfjdsf"))
